package com.yichen.rent.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.yichen.rent.pojo.User;
import com.yichen.rent.service.UserService;
import com.yichen.rent.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import util.JwtUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangchenbin
 * @date 2020-02-28
 * @description
 */
@Slf4j
@Controller
@RequestMapping("/system")
public class SystemController {

    @Autowired
    private RestTemplate restTemplate;


    @Autowired
    private RedisUtils redisUtils;

    @Value("${system.corpid}")
    private String corpid;

    @Value("${system.corpsecret}")
    private String corpsecret;

    private String corpsecretKey = "app_token";

    @Value("${system.scansecret}")
    private String scansecret;

    private String scansecretKey = "scan_token";
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;

    @RequestMapping("/scan")
    public String scan(String code, HttpSession session, HttpServletResponse response) {

        String url = getUserInfoUrl(code, scansecret, scansecretKey);
        System.out.println(url + " 获取用户信息");

        try {
            String result = restTemplate.getForObject(url, String.class);
            JSONObject jsonObject = JSONObject.parseObject(result);
            Integer errcode = (Integer) jsonObject.get("errcode");
            if (errcode != null && errcode != 0) {
                if (errcode == 40014) {
                    updateToken(scansecret, scansecretKey);
                    return "redirect:/rent/system/scan?code=" + code;


                }
                System.out.println(errcode);
                return "redirect:/admin/index.html";
            } else {
                String userId = (String) jsonObject.get("UserId");
                System.out.println(userId);
                //User user = userService.getByUsername(userId);
                /*if (user == null) {
                    return "redirect:/login.html";
                } else if (user.getState() != 0) {
                    return "redirect:/login.html";
                }*/
                String token = jwtUtil.createJWT(userId, "员工", "admin");
                session.setAttribute("uid",userId);
                session.setAttribute("usertype","员工");
                Cookie cookie = new Cookie("Admin-Token",token);
                response.addCookie(cookie);
                try {

                    session.setMaxInactiveInterval(60 * 60 * 12);
                    return "redirect:/admin/index.html";
                } catch (Exception e) {
                    e.printStackTrace();

                }
                return "redirect:/admin/index.html";


            }
        } catch (Exception e) {
            e.printStackTrace();

            return "redirect:/rent/admin/index.html";

        }
    }


    @ResponseBody
    @GetMapping("/uid")
    public Map<String, Object> getInfo(HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        System.out.println(session.getAttribute("uid"));
        map.put("uid", session.getAttribute("uid"));
        return map;
    }

    private String getUserInfoUrl(String code, String secret, String key) {
        String accessToken = getAccessTokenForRedis(secret, key);
        return "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" + accessToken + "&code=" + code;
    }

    private String getAccessTokenForWeXin(String secret) {
        log.info("企业微信获取token" + LocalTime.now());
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + secret;
        System.out.println(url);
        String result = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSON.parseObject(result);
        Integer errcode = (Integer) jsonObject.get("errcode");
        if (errcode != null && errcode != 0) {
            return null;
        } else {
            return (String) jsonObject.get("access_token");
        }
    }

    private String getAccessTokenForRedis(String secret, String key) {

        if (StringUtils.isEmpty(redisUtils.get("access_token"))) {
            System.out.println("从微信获取token");
            redisUtils.set(key, getAccessTokenForWeXin(secret), 7100, TimeUnit.SECONDS);
            System.out.println(redisUtils.get(key));
        }
        System.out.println("从redis获取");
        return redisUtils.get(key);
    }

    private void updateToken(String key, String secret) {
        redisUtils.getAndSet(key, getAccessTokenForWeXin(secret));
    }
}
